package com.stoneframe.controller.manageAuthorize;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stoneframe.controller.base.BaseGenericController;
import com.stoneframe.entity.other.TreeEntity;
import com.stoneframe.service.BaseService;
import com.stoneframe.service.manageAuthorize.SysAuthorizeService;
import com.stoneframe.service.manageSystem.SysDepartmentService;
import com.stoneframe.service.manageSystem.SysOrganizeService;
import com.stoneframe.service.manageSystem.SysRoleService;
import com.stoneframe.util.baseApp.AppHelper;
import com.stoneframe.util.baseApp.PageData;
import com.stoneframe.util.baseJson.JsonHelper;
import com.stoneframe.util.baseJson.TreeJsonHelper;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Controller
@RequestMapping(value="sysPermissionRole")
public class SysPermissionRoleController extends BaseGenericController {
	
	@Resource(name="sysAuthorizeService")
	private SysAuthorizeService sysAuthorizeService;
	@Resource(name="sysOrganizeService")
	private SysOrganizeService sysOrganizeService;
	@Resource(name="sysDepartmentService")
	private SysDepartmentService sysDepartmentService;
	@Resource(name="sysRoleService")
	private SysRoleService sysRoleService;

	@Override
	public BaseService getService() {
		// TODO Auto-generated method stub
		return sysAuthorizeService;
	}
	
	//获取部门树Json
	@RequestMapping(value="treeDepartTree",produces="text/plain;charset=UTF-8")
	@ResponseBody
	public Object treeDepartTree(String roleId){
		logBefore(logger, className+"treeDepartTree");
		PageData pd=this.getPageData();
		List<TreeEntity> treeList=new ArrayList();
		try{
			PageData roleData=sysRoleService.findById(new PageData("keyValue",roleId));
			PageData organizeEntity=sysOrganizeService.findById(new PageData("keyValue",roleData.getString("organizeId")));
			List<PageData> departList=sysDepartmentService.listAll(new PageData("organizeId",roleData.getString("organizeId")));
			TreeEntity tree=new TreeEntity();
			tree.setId(organizeEntity.getString("organizeId"));
            tree.setText(organizeEntity.getString("organizeName"));
            tree.setValue(organizeEntity.getString("organizeId"));
            tree.setIsexpand(true);
            tree.setComplete(true);
            tree.setHasChildren(true);
            tree.setParentId("0");
            treeList.add(tree);
            for(PageData departData:departList){
            	tree=new TreeEntity();
            	Boolean hasChildren =false;
				for(PageData subData:departList){
					if(subData.getString("parentId").equals(departData.getString("departmentId"))){
						hasChildren=true;
						break;
					}
				}
				tree.setId(departData.getString("departmentId"));
	            tree.setText(departData.getString("departmentName"));
	            tree.setValue(departData.getString("departmentId"));
	            tree.setIsexpand(true);
	            tree.setComplete(true);
	            tree.setHasChildren(hasChildren);
	            tree.setParentId(departData.getString("parentId").equals("0")?departData.getString("organizeId"):departData.getString("parentId"));
	            treeList.add(tree);
            }
			logAfter(logger);
			return AppHelper.returnObject(pd, TreeJsonHelper.treeToJson(treeList, "0"));
		}catch(Exception e){
			logger.error(e.toString(), e);
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
	//获取用户列表
	@RequestMapping(value="getMemberUser")
	@ResponseBody
	public Object getMemberUser(String roleId){
		logBefore(logger, className+"getMemberUser");
		try{
			List<PageData> list=sysAuthorizeService.getMemberUser(roleId);
			
			logAfter(logger);
			return AppHelper.returnObject(new PageData(), list);
		}catch(Exception e){
			logger.error(e.toString(), e);
			return AppHelper.errorObject(e.getMessage());
		}
		
	}
	
	//获取模块数Json
	@RequestMapping(value="treeModuleTree",produces="text/plain;charset=UTF-8")
	@ResponseBody
	public Object treeModuleTree(String roleId){
		logBefore(logger, className+"treeModuleTree");
		
		PageData pd=this.getPageData();
		List<PageData> existModule=null;
		List<PageData> list=null;
		List<TreeEntity> treeList = new ArrayList();
		try{
			existModule=sysAuthorizeService.getModulePermission(new PageData("objectId",roleId));
			list=sysAuthorizeService.getModuleList();
			for(PageData sysModulePageData:list){
				TreeEntity tree=new TreeEntity();
				Boolean hasChildren =false;
				for(PageData subModulePageData:list){
					if(subModulePageData.getString("parentId").equals(sysModulePageData.getString("moduleId"))){
						hasChildren=true;
						break;
					}
				}
				int hasCheckState =0;
				for(PageData subData:existModule){
					if(subData.getString("itemId").equals(sysModulePageData.getString("moduleId"))){
						hasCheckState=1;
						break;
					}
				}
                tree.setId(sysModulePageData.getString("moduleId"));
                tree.setText(sysModulePageData.getString("moduleName"));
                tree.setValue(sysModulePageData.getString("moduleId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(hasChildren);
                tree.setParentId(sysModulePageData.getString("parentId"));
                tree.setImg(sysModulePageData.getString("moduleIcon"));
                tree.setCheckState(hasCheckState);
				
				treeList.add(tree);
			}
			
		}catch(Exception e){
			logger.error(e.toString(),e);
			return AppHelper.errorObject(e.getMessage());
		}

		logAfter(logger);
		return AppHelper.returnObject(pd,TreeJsonHelper.treeToJson(treeList, "0"));
		
	}
	
	//获取按钮树Json
	@RequestMapping(value="treeModuleButtonList",produces="text/plain;charset=UTF-8")
	@ResponseBody
	public Object treeModuleButtonList(String roleId) throws Exception{
		logBefore(logger, className+"treeModuleButtonList");
		PageData pd=this.getPageData();
		List<TreeEntity> treeList=new ArrayList();
		try{
			List<PageData> existModule=sysAuthorizeService.getModulePermission(new PageData("objectId",roleId));
			List<PageData> existModuleButton=sysAuthorizeService.getModuleButtonPermission(new PageData("objectId",roleId));
			List<PageData> moduleList=sysAuthorizeService.getModuleList();
			List<PageData> moduleButtonList=sysAuthorizeService.getModuleButtonList();
			for(PageData modulePageData:moduleList){
				TreeEntity tree=new TreeEntity();
				int hasCheckState =0;
				for(PageData subData:existModule){
					if(subData.getString("itemId").equals(modulePageData.getString("moduleId"))){
						hasCheckState=1;
						break;
					}
				}
				tree.setId(modulePageData.getString("moduleId"));
                tree.setText(modulePageData.getString("moduleName"));
                tree.setValue(modulePageData.getString("moduleId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(true);
                tree.setParentId(modulePageData.getString("parentId"));
                tree.setImg(modulePageData.getString("moduleIcon"));
                tree.setCheckState(hasCheckState);
                
                treeList.add(tree);
			}
			for(PageData buttonPageData:moduleButtonList){
				TreeEntity tree=new TreeEntity();
				Boolean hasChildren =false;
				for(PageData subModulePageData:moduleButtonList){
					if(subModulePageData.getString("parentId").equals(buttonPageData.getString("buttonId"))){
						hasChildren=true;
						break;
					}
				}
				int hasCheckState =0;
				for(PageData subData:existModuleButton){
					if(subData.getString("itemId").equals(buttonPageData.getString("buttonId"))){
						hasCheckState=1;
						break;
					}
				}
				tree.setId(buttonPageData.getString("buttonId"));
                tree.setText(buttonPageData.getString("buttonName"));
                tree.setValue(buttonPageData.getString("buttonId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(hasChildren);
                tree.setParentId(buttonPageData.getString("parentId").equals("0")?buttonPageData.getString("moduleId"):buttonPageData.getString("parentId"));
                tree.setImg(buttonPageData.getString("buttonIcon"));
                tree.setCheckState(hasCheckState);
                
                treeList.add(tree);
			}
			
			logAfter(logger);
			return AppHelper.returnObject(pd, TreeJsonHelper.treeToJson(treeList, "0"));
		}catch(Exception e){
			logger.error(e.toString(),e);
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
	//获取视图树Json
	@RequestMapping(value="treeModuleColumnList",produces="text/plain;charset=UTF-8")
	@ResponseBody
	public Object treeModuleColumnList(String roleId) throws Exception{
		logBefore(logger, className+"");
		PageData pd=this.getPageData();
		List<TreeEntity> treeList=new ArrayList();
		try{
			List<PageData> existModule=sysAuthorizeService.getModulePermission(new PageData("objectId",roleId));
			List<PageData> existModuleColumn=sysAuthorizeService.getModuleColumnPermission(new PageData("objectId",roleId));
			List<PageData> moduleList=sysAuthorizeService.getModuleList();
			List<PageData> moduleColumnList=sysAuthorizeService.getModuleColumnList("");
			for(PageData modulePageData:moduleList){
				TreeEntity tree=new TreeEntity();
				int hasCheckState =0;
				for(PageData subData:existModule){
					if(subData.getString("itemId").equals(modulePageData.getString("moduleId"))){
						hasCheckState=1;
						break;
					}
				}
				tree.setId(modulePageData.getString("moduleId"));
                tree.setText(modulePageData.getString("moduleName"));
                tree.setValue(modulePageData.getString("moduleId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(true);
                tree.setParentId(modulePageData.getString("parentId"));
                tree.setImg(modulePageData.getString("moduleIcon"));
                tree.setCheckState(hasCheckState);
                
                treeList.add(tree);
			}
			for(PageData columnPageData:moduleColumnList){
				TreeEntity tree=new TreeEntity();
				Boolean hasChildren =false;
				for(PageData subPageData:moduleColumnList){
					if(subPageData.getString("parentId").equals(columnPageData.getString("columnId"))){
						hasChildren=true;
						break;
					}
				}
				int hasCheckState =0;
				for(PageData subData:existModule){
					if(subData.getString("itemId").equals(columnPageData.getString("columnId"))){
						hasCheckState=1;
						break;
					}
				}
				tree.setId(columnPageData.getString("columnId"));
                tree.setText(columnPageData.getString("columnName"));
                tree.setValue(columnPageData.getString("columnId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(hasChildren);
                tree.setParentId(columnPageData.getString("parentId").equals("0")?columnPageData.getString("moduleId"):columnPageData.getString("parentId"));
                tree.setImg("fa fa-filter "+columnPageData.getString("moduleId"));
                tree.setCheckState(hasCheckState);
                
                treeList.add(tree);
			}
			
			logAfter(logger);
			return AppHelper.returnObject(pd, TreeJsonHelper.treeToJson(treeList, "0"));
		}catch(Exception e){
			logger.error(e.toString(),e);
			return AppHelper.errorObject(e.getMessage());
		}
	}

	//获取数据权限树Json
	@RequestMapping(value="treeOrganizeList")
	@ResponseBody
	public Object treeOrganizeList() throws Exception{
		logBefore(logger, className+"treeOrganizeList");
		
		PageData pd=this.getPageData();
		Map<String,Object> map=new HashMap<String,Object>();
		List<TreeEntity> treeList=new ArrayList();
		try{
			List<PageData> existAuthorizeData=sysAuthorizeService.getAuthorizeDataList(pd);
			List<PageData> departmentList=sysDepartmentService.listAll(pd);
			for(PageData departData:departmentList){
				TreeEntity tree=new TreeEntity();
				Boolean hasChildren =false;
				for(PageData subData:departmentList){
					if(subData.getString("parentId").equals(departData.getString("departmentId"))){
						hasChildren=true;
						break;
					}
				}
				int hasCheckState=0;
				for(PageData subData:existAuthorizeData){
					if(subData.getString("resourceId").equals(departData.getString("departmentId"))){
						hasCheckState=1;
						break;
					}
				}
				tree.setId(departData.getString("departmentId"));
                tree.setText(departData.getString("departmentName"));
                tree.setValue(departData.getString("departmentId"));
                tree.setShowCheck(true);
                tree.setIsexpand(true);
                tree.setComplete(true);
                tree.setHasChildren(hasChildren);
                tree.setParentId(departData.getString("parentId"));
                tree.setCheckState(hasCheckState);
                
                treeList.add(tree);
			}
			
			int authorizeType=-1;
			if(existAuthorizeData.size()>0){
				authorizeType=Integer.parseInt(existAuthorizeData.get(0).get("authorizeType").toString());
			}
			
			map.put("authorizeType", authorizeType);
			map.put("authorizeData", existAuthorizeData);
			map.put("treeJson", TreeJsonHelper.treeToJson(treeList, "0"));
			
			logAfter(logger);
			return AppHelper.returnObject(pd, map);
		}catch(Exception e){
			logger.error(e.toString(),e);
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
	@RequestMapping(value="saveMember")
	@ResponseBody
	public Object saveMember(String roleId,String userIds){
		logBefore(logger, className+"saveMember");
		try{
			String[] arrUserId=userIds.split(",");
			sysAuthorizeService.saveMember(2,roleId,arrUserId);
			
			logAfter(logger);
			return AppHelper.successObject("保存成功。");
		}catch(Exception e){
			logger.error(e.toString(), e);
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
	@RequestMapping(value="saveAuthorize")
	@ResponseBody
	public Object saveAuthorize(String roleId, String moduleIds, String moduleButtonIds, String moduleColumnIds, String authorizeDataJson){
		logBefore(logger, className+"saveAuthorize");
		try{
			String[] arrModuleId=moduleIds.split(",");
			String[] arrModuleButtonId=moduleButtonIds.split(",");
			String[] arrModuleColumnId=moduleColumnIds.split(",");
			ObjectMapper objectMapper=new ObjectMapper();
			List<Map<String, Object>> authorizeDataList=objectMapper.readValue(authorizeDataJson, List.class);
			
			sysAuthorizeService.saveAuthorize(2,roleId,arrModuleId,arrModuleButtonId,arrModuleColumnId,authorizeDataList);
			
			logAfter(logger);
			return AppHelper.successObject("保存成功。");
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
}
